package com.twohand.admin.Interceptor;


import com.alibaba.fastjson2.JSON;
import com.twohand.admin.Config.filter.HttpHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Set;

@Component
public class Request implements HandlerInterceptor {
    private long time;
    Logger log = LoggerFactory.getLogger(Request.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        time = System.currentTimeMillis();
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        long l = System.currentTimeMillis();
//        Map<String,String[]> parameterMap = request.getParameterMap();
//        Set<String> keyset = parameterMap.keySet();
//        String params = "";
//        for(String name:keyset){
//            String[] values = parameterMap.get(name);
//            params+=name+":";
//            for(String value:values){
//                params+=value+";";
//            }
//            params+=",";
//        }
        String params = HttpHelper.getBodyString(request);
        if(StringUtils.isEmpty(params)){
            params = JSON.toJSONString(request.getParameterMap());
        }
        request.setAttribute("reqMsg",request.getMethod()+"---"+request.getRequestURI()+"---请求耗时"+(l-time)+"ms");
        log.info(request.getMethod()+"---"+request.getRequestURI()+"---请求参数:"+params+"---请求耗时"+(l-time)+"ms");
    }
}
